package com.knowledge.plus.创建线程and线程池.注解创建线程.controller;

import com.knowledge.plus.创建线程and线程池.注解创建线程.service.IExecuteService;
import com.knowledge.plus.创建线程and线程池.注解创建线程.service.TestAsyncService;
import com.knowledge.plus.创建线程and线程池.注解创建线程.service.impl.TestAsyncServiceImpl;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 注解 @Async 指定线程池实现异步
 *
 * @author TPF
 * @since 2022/9/29
 */
@RestController
@RequestMapping("task")
class AsyncDemoController {

    @Resource
    private IExecuteService executeService;

    @Resource
    private TestAsyncService asyncService;

    /**
     * 示例 1：接口调用返回更早，说明异步成功
     * 接口添加异步注解@Async {@link IExecuteService}
     */
    @GetMapping("execute1")
    public String ExecuteTest() {
        System.out.println("execute1: id = " + Thread.currentThread().getId() + "；name = " + Thread.currentThread().getName());
        executeService.sleepingTest();
        return "suc! id = " + Thread.currentThread().getId() + "；name = " + Thread.currentThread().getName();
    }

    /**
     * 示例2：接口调用返回更早，说明异步成功
     * 实现类添加异步注解@Async {@link TestAsyncServiceImpl}
     */
    @GetMapping("execute2")
    public String asyncTest() throws InterruptedException {
        System.out.println("execute2: 当前线程 id = " + Thread.currentThread().getId() + "；name = " + Thread.currentThread().getName());
        asyncService.asyncService();
        return "suc! id = " + Thread.currentThread().getId() + "；name = " + Thread.currentThread().getName();
    }


}
